<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleCancel"
      :show-close="true"
      :append-to-body="true"
      :close-on-click-modal="true"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="deal-dialog"
      width="400px"
      @open="openDialog"
    >
      <Title title="退货处理" font-size="16px" style="margin-bottom:16px;"/>
      <div v-if="isBatchHandel">
        <el-form ref="batchForm" :model="paramsObj" :rules="batchRules" label-position="right" label-width="90px">
          <el-form-item label="货物状态:" prop="goodsStatus">
            <el-select v-model="paramsObj.goodsStatus" size="small" placeholder="请选择" class="width240">
              <el-option
                v-for="item in goodsStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <p class="tip">注意：货物设置为已寄回，请对寄回的商品进行SKU编码和数量填写。</p>
      </div>
      <el-form v-else ref="form" :model="paramsObj" :rules="rules" label-position="right" label-width="110px">
        <el-form-item label="退货编号(淘宝):">
          <span>{{ paramsObj.taobaoSn || '--' }}</span>
        </el-form-item>
        <el-form-item label="订单编号:">
          <span>{{ paramsObj.orderNum || '--' }}</span>
        </el-form-item>
        <el-form-item label="货物状态:">
          <el-select v-model="paramsObj.goodsStatus" size="small" placeholder="请选择" class="width240">
            <el-option
              v-for="item in goodsStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="paramsObj.goodsStatus === 3" label="SKU编码:" prop="goodsCoding">
          <el-select
            v-model="paramsObj.goodsCoding"
            size="small"
            placeholder="请选择SKU编码"
            class="width240"
            popper-class="global-select-down"
            @change="selectGoodsCoding">
            <el-option
              v-for="item in goodsInfo"
              :key="item.id"
              :label="item.goodsCoding+`(${item.warehouse})`"
              :value="item.goodsCoding" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item v-if="paramsObj.goodsStatus === 3" label="订单商品数量:">
          <span>{{ paramsObj.quantity || '--' }}</span>
        </el-form-item> -->
        <el-form-item v-if="paramsObj.goodsStatus === 3" label="退货商品数量:" prop="returnsCount">
          <el-input
            v-model="paramsObj.returnsCount"
            oninput="if(value>999999999)value=999999999;if(value<1)value=1;"
            name="returnNums"
            type="number"
            placeholder="退货商品数量"
            size="small"
            class="width240"
            @input="valToPureNum($event)" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleSubmit">确认</el-button>
        <el-button type="info" class="cancel-btn-style" size="small" @click="handleCancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';
import { getSkuList, returnSale, getGoodsInfo, batchReturnSale } from '@/api/mengli';
// import { getSkuList } from '@/api/mengli';

export default {
  components: { Title },
  model: {
    prop: 'paramsObj',
    event: 'change'
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    paramsObj: {
      type: Object,
      default() {
        return {};
      }
    },
    isBatchHandel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      goodsStatusOptions: [
        { value: 0, label: '未发货' },
        { value: 1, label: '未收到发货' },
        { value: 2, label: '已收到货' },
        { value: 3, label: '已寄回' }
      ],
      goodsCodingList: [],
      getSkuList,
      batchRules: {
        goodsStatus: [{ required: true, trigger: 'change', message: '请选择货物状态' }]
      },
      rules: {
        goodsCoding: [{ required: true, trigger: 'change', message: '请选择SKU编码' }],
        returnsCount: [{ required: true, trigger: 'input', message: '请输入退货商品数量' }]
      },
      goodsInfo: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    valToPureNum(val) {
      if (val) this.paramsObj.number = val.replace(/[^\d]/g, '');
    },
    openDialog() {
      this.$refs.batchForm && this.$refs.batchForm.resetFields();
      this.$refs.form && this.$refs.form.resetFields();
      if (!this.isBatchHandel) {
        getGoodsInfo(this.paramsObj.orderNum).then(res => {
          this.goodsInfo = res.data.goodsInfo;
        }).catch(err => {
          console.log(err);
        });
      }
    },
    selectGoodsCoding(val) {
      const temp = this.goodsInfo.filter(item => {
        return item.goodsCoding === val;
      });
      this.paramsObj.warehouseId = temp[0].warehouseId;
      // this.paramsObj.quantity = temp[0].quantity || '--';
    },
    closeDialog() {
      this.$emit('closeDealDialog');
    },
    handleSubmit() {
      if (this.isBatchHandel) {
        this.$refs['batchForm'].validate(valid => {
          if (valid) {
            this.handelPost(this.paramsObj);
          } else {
            return false;
          }
        });
      } else {
        const recordData = {
          orderNum: this.paramsObj.orderNum,
          cost: 1,
          totalCost: 100,
          inventoryCount: this.paramsObj.returnsCount
        };
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.handelPost(recordData);
          } else {
            return false;
          }
        });
        // this.$emit('openRecordDialog', recordData);
        // this.handelPost(recordData);
      }
    },
    isShowRecordDialog() {
      return this.paramsObj.goodsStatus === 3 && this.paramsObj.goodsCoding && this.paramsObj.returnsCount;
    },
    handelPost(recordData) {
      if (this.isBatchHandel) {
        // 批量修改状态
        batchReturnSale(this.paramsObj).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功！');
          }
          this.$emit('closeDealDialog', res.code);
        }).catch(err => {
          console.log(err);
          this.$emit('closeDealDialog');
        });
      } else {
        // 单个修改
        const { goodsStatus, goodsCoding, warehouseId, returnsCount } = this.paramsObj;
        const params = {
          id: this.paramsObj.ids,
          goodsStatus, goodsCoding, warehouseId, returnsCount
        };
        returnSale(params).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功！');
          }
          recordData.cost = res.data.cost;
          recordData.totalCost = res.data.totalCost;
          recordData.id = res.data.mengliStockBatchId;
          this.$emit('closeDealDialog', {
            mengliStockBatchId: res.data.mengliStockBatchId,
            number: res.data.number,
            goodsStatus,
            goodsCost: res.data.cost
          });
          if (res.data.mengliStockBatchId) {
            this.$emit('openRecordDialog', recordData);
          }
        }).catch(err => {
          console.log(err);
        });
      }
    },
    handleCancel() {
      /* this.$refs.batchForm && this.$refs.batchForm.resetFields();
      this.$refs.form && this.$refs.form.resetFields(); */
      this.$emit('closeDealDialog');
    }
  }
};
</script>

<style lang="scss" scoped>
.deal-dialog {
  border-radius: 10px;
  ::v-deep {
    .el-dialog{
      border-radius: 10px;
    }
    .el-dialog__header{
      padding: 0;
    }
    .el-dialog__body{
      padding: 16px 24px 0;
    }
    .dialog-footer{
      display: flex;
      justify-content: center;
    }
    .el-form-item{
      margin-bottom: 14px;
      .width240{
        width: 240px;
      }
      .el-form-item__error{
        padding: 0;
      }
    }
    .tip{
      color: #999;
      padding: 0 10px;
    }
  }
}
</style>
